import React, { useContext } from 'react'
import Store from './context'
import { DEL_TODO, TOGGLE_COMPLETE } from './reducer'

const TodoList = () => {
    const { state, dispatch } = useContext(Store)
    console.log('TodoList 列表组件====>>>')
    console.log(state)
    // 按diplay条件过滤数据
    const filterDisplay = () =>
        state.todos.filter(item => {
            switch (state.display) {
                case 'completed':
                    return item.isComplete
                case 'uncompleted':
                    return !item.isComplete
                case 'all':
                default:
                    return true
            }
        })
    // 完成
    const todoChange = e => {
        dispatch({
            type: TOGGLE_COMPLETE,
            payload: e.target.value
        })
    }
    // 删除
    const delClick = e => {
        dispatch({
            type: DEL_TODO,
            payload: e.target.dataset.id
        })
    }
    return (
        <div>
            <ul>
            {filterDisplay().map((todo, index) => (
                  <li key={index}>
                      <input
                            type="checkbox"
                            value={todo.id}
                checked={todo.isComplete}
                onChange={todoChange} />
                      {todo.isComplete ? <del>{todo.title}</del> : <span>{todo.title}</span>}
                      <button type="danger" data-id={todo.id} onClick={delClick}>
                            删除
                        </button>
                    </li>
                ))}
            </ul>
      </div>
    )
}

export default TodoList
